import Vue from 'vue'
import Vuex from 'vuex'

Vue.use(Vuex)

export default new Vuex.Store({
  state: {
    token: localStorage.getItem('token'),
    user: {
      userId: localStorage.getItem('userId'),
      userName: localStorage.getItem('userName'),
      userImg: localStorage.getItem('userImg')
    },
    requestFriend: localStorage.getItem('requestFriend') != null ? JSON.parse(localStorage.getItem('requestFriend')) : [],
    contactList: '',
    chatList: localStorage.getItem('chatList') != null ? JSON.parse(localStorage.getItem('chatList')) : [],
    isChatting: false,
    wsIsLive: false,
  },
  mutations: {
    saveToken(state, token) {
      state.token = token;
    },
    saveUser(state, user) {
      state.user = user;
    },
    saveRequest(state, requestFriend) {
      state.requestFriend = requestFriend;
    },

    saveContactList(state, contactList) {
      state.contactList = contactList;
    },

    saveChatList(state, chatList) {
      state.chatList = chatList;
    },

    updateIsChatting(state, status) {
      state.isChatting = status;
    },

    updateWsIsLive(state, status) {
      state.wsIsLive = status;
    }
  },
  actions: {
    asyncSaveToken(context, token) {
      localStorage.setItem('token', token);
      context.commit('saveToken', token);
    },

    asyncSaveUser(context, user) {
      localStorage.setItem('userId', user.userId);
      localStorage.setItem('userName', user.userName);
      localStorage.setItem('userImg', user.userImg);
      context.commit('saveUser', user);
    },

    asyncSaveRequest(context, requestFriend) {
      localStorage.setItem('requestFriend', JSON.stringify(requestFriend));
      context.commit('saveRequest', requestFriend);
    },

    asyncSaveContactList(context, contactList) {
      context.commit('saveContactList', contactList);
    },

    asyncSaveChatList(context, chatList) {
      localStorage.setItem('chatList', JSON.stringify(chatList));
      context.commit('saveChatList', chatList);
    }
  },
  getters: {
    getReqFriendNum(state) {
      let requestFriend = state.requestFriend;
      let num = 0;
      requestFriend.forEach(element => {
        if (element.status == 1) {
          num++;
        }
      });
      return num;
    },
    //获取未读消息总数
    getUnreadChatNum(state) {
      let num = 0;
      state.chatList.forEach(item => {
        num += item.count;
      });
      return num;
    }
  },
  modules: {
  }
})
